<?php

namespace App\Http\Controllers\Api\V1;

use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use Validator;

class AudioController extends Controller
{
    const PUBLIC_DIR = 'public/public/audios/';
    const SAVE_DIR = 'public/user/audios/';
    const SHOW_DIR = 'storage/user/audios/';

    /**
     * @SWG\Get(
     *     summary="公共音频列表",
     *     path="/audio/public",
     *     description="获取公共音频列表",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function public_audios(Request $request)
    {
        $dir = self::PUBLIC_DIR;

        $paths = Storage::allFiles($dir);

        foreach ($paths as &$audio) {
            $audio = str_replace('public/', env('APP_URL') . 'storage/', $audio);
        }

        return $paths ? $paths : [];
    }

    /**
     * @SWG\Get(
     *     summary="用户音频列表",
     *     path="/audio",
     *     description="获取用户音频列表",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function index(Request $request)
    {
        $path = self::SAVE_DIR . substr(md5($request->user()->id), 8, 16) . '/';

        $paths = Storage::allFiles($path);

        foreach ($paths as &$audio) {
            $audio = str_replace('public/', env('APP_URL') . 'storage/', $audio);
        }

        return $paths ? $paths : [];
    }

    /**
     * @SWG\Post(
     *     summary="用户上传音频",
     *     path="/audio",
     *     description="用户上传音频",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="file-audio",
     *         in="query",
     *         description="音频(base64)",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function store(Request $request)
    {
        $rules = [
            'file-audio' => ['required']
        ];
        $messages = [
            'file-audio.required' => '请上传音频'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            throw new StoreResourceFailedException('create error', $validator->errors());
        }

        $types = ['jpg', 'gif', 'png', 'jpeg'];
        $audio = $request->file('file-audio');
        if ($audio->isValid()) {
            // 获取文件相关信息
//            $originalName = $audio->getClientOriginalName(); // 文件原名
            $ext = $audio->getClientOriginalExtension();     // 扩展名
            $realPath = $audio->getRealPath();   //临时文件的绝对路径
//            $type = $audio->getClientMimeType();     // image/jpeg

            if (!in_array($ext, $types)) {
                throw new StoreResourceFailedException('format error');
            }

            // 上传文件
            $path = substr(md5($request->user()->id), 8, 16) . date('/Y/md/');
            $filename = uniqid() . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            Storage::disk('local')->put(self::SAVE_DIR . $path . $filename, file_get_contents($realPath));

            return ['path' => env('APP_URL') . self::SHOW_DIR . $path . $filename];
        } else {
            throw new StoreResourceFailedException('format error');
        }
    }

    /**
     * @SWG\Delete(
     *     summary="用户删除音频",
     *     path="/audio",
     *     description="用户删除音频",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="audio",
     *         in="query",
     *         description="音频名称(只需要文件名)",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     ),
     * )
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function destroy(Request $request)
    {
        $audioArray = explode('/', $request->audio);
        $audio = $audioArray[count($audioArray) - 2] . '/';
        $audio .= $audioArray[count($audioArray) - 1];

        $path = self::SAVE_DIR . substr(md5($request->user()->id), 8, 16) . '/';

        Storage::delete($path . $audio);

        return ['success' => true];
    }
}
